package com.learn.window;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @create: 2023-04-19 16:18
 * @author: Mr.Du
 * --------------
 * @notes:  滑动计数窗口
 **/
public class SlidingCountWindowDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // Source
        DataStreamSource<String> source = env.socketTextStream("node1", 9999);
        SingleOutputStreamOperator<Tuple2<String, Integer>> operator = source.map(word -> Tuple2.of(word, 1)).returns(Types.TUPLE(Types.STRING, Types.INT));

        // 统计全部数据, 每隔5条, 统计前10条数据
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumAll = operator
                .countWindowAll(10, 5).sum(1);

        // 统计每个key分组后的数据, 每隔5条
        // 这个5条是每个分组内达到5条, 而不是总的达到5条
        SingleOutputStreamOperator<Tuple2<String, Integer>> sumEachKey = operator
                .keyBy(0).countWindow(10, 5).sum(1);

        sumAll.print("Sum all>>>");
        sumEachKey.print("Sum each key>>>");

        env.execute();
    }
}
